<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/3/5
 * Time: 17:26
 */

namespace app\teacher\controller;


use app\api\model\ask\Ask;
use app\api\model\ask\AskAnswer;
use app\teacher\lib\ApiResponse;
use app\teacher\lib\TeacherBaseController;
use think\Db;
use think\Request;

class Asks extends TeacherBaseController
{
    public function list(Request $request) {
        $status = $request->param('status',-1);
        $result = Ask::teacherManageList($this->teacherId, $this->rows, $this->page, $status);
        return ApiResponse::success($result);
    }

    public function answer(Request $request) {
        $ask_id = $request->param('ask_id');
        $ask = Ask::get(['ask_id'=>$ask_id,'ask_teacher'=>$this->teacherId]);
        if (empty($ask)) return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'问题不存在或无效');
        if (Ask::STATUS_EXPIRED == $ask->ask_id) return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'问题已过期');

        $answer = AskAnswer::get(['ask_id' => $ask->ask_id]);
        if ($request->isGet()) {
            return ApiResponse::success($answer);
        } elseif ($request->isPost()) {
            $form = $this->validFormData([
                ['content', 'require', '内容不能为空'],
                ['img', 'array',],
            ]);
            if (empty($answer)) {
                $answer = new AskAnswer();
                $answer->ask_id = $ask->ask_id;
                $answer->teacher_id = $this->teacherId;
            }
            $answer->content = $form['content'];
            $answer->img = $form['img'] ?? [];

            Db::transaction(function () use ($answer) {
                $answer->save();
                $ask = Ask::get($answer->ask_id);
                $ask->answer_time = date('Y-m-d H:i:s');
                $ask->ask_status = 1;
                $ask->save();
            });

            return ApiResponse::success();
        } else {
            return json([],405);
        }
    }

}